package com.hangzhou.xyj.ui.activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.net.handler.UpdatePasswordHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.UpdatePasswordReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;

/**
 * 更新密码界面
 */
public class UpdatePasswordActivity extends BaseActivity implements View.OnClickListener {
    private EditText mEtOldPwd;//老密码
    private EditText mEtNewPwd;//新密码
    private Button mBtnConfirm;//确定

    @Override
    public void initTop() {
        enableNetErrorView(false);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_update_password);
    }

    @Override
    public void initViews() {
        mEtOldPwd = (EditText) findViewById(R.id.et_old_password);
        mEtNewPwd = (EditText) findViewById(R.id.et_new_password);
        mBtnConfirm = (Button) findViewById(R.id.btn_confirm);
    }

    @Override
    public void initDatas() {
    }

    @Override
    public void initListeners() {
        mEtOldPwd.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm://确定按钮
                if (checkInput()) {
                    String oldPwd = mEtOldPwd.getText().toString().trim();
                    String newPwd = mEtNewPwd.getText().toString().trim();
                    updatePwd(oldPwd,newPwd);
                }
                break;
        }
    }

    /**
     * 更新密码
     * @param oldPwd
     * @param newPwd
     */
    private void updatePwd(String oldPwd, String newPwd) {
        String userId = XYJApplication.getInstance().getUserInfo().getUserId();
        UpdatePasswordReq req = new UpdatePasswordReq(userId,oldPwd,newPwd);
        HttpLoader.getInstance().sendRequest(new UpdatePasswordHandler(req, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                if ((Boolean)model) {
                    ToastUtil.show("修改密码成功");
                    closeActivity();
                }
            }
        },0));
    }

    /**
     * 校验输入
     * @return
     */
    private boolean checkInput() {
        String oldPwd = mEtOldPwd.getText().toString().trim();
        if (StringUtil.isBlank(oldPwd)) {
            ToastUtil.show("请输入旧密码");
            return false;
        }

        String newPwd = mEtNewPwd.getText().toString().trim();
        if (StringUtil.isBlank(newPwd)) {
            ToastUtil.show("请输入新密码");
            return false;
        }
        return true;
    }

}
